extends TileMap


signal entered_map(map)
signal entered_intersection(next_map, pos)


var current_pos : Vector2 = Vector2.INF
var next_maps : Dictionary = {}
var open : bool = false


onready var label = $Label


##  获取传送到这个区域的位置
## @dir  路口方向，进入到哪个路口的方向
func get_delivery(dir: Vector2) -> Vector2:
	var data = {
		Vector2.RIGHT: $Left.global_position + Vector2(32, 0),
		Vector2.LEFT: $Right.global_position + Vector2(-32, 0),
		Vector2.DOWN: $Up.global_position + Vector2(0, 32),
		Vector2.UP: $Down.global_position + Vector2(0, -32),
	}
	# 确保data中存在这个方向，否则报错
	assert(data.has(dir), "没有这个方向！")
	return data[dir]


##  设置地图所在位置
func set_map_pos(pos: Vector2):
	current_pos = pos
	if label == null:
		yield(self, "ready")
	label.text = str(pos)


##  连接地图
## @map  对应路口的地图（用于下面进入当前的路口区域后，要发出的下一个路口的位置）
## @map_pos  这个地图的位置
func connect_map(map, map_pos: Vector2):
	var d = map_pos - current_pos
	# 左
	if d.x < 0:
		next_maps[Vector2.LEFT] = map
	# 右
	elif d.x > 0:
		next_maps[Vector2.RIGHT] = map
	# 上
	elif d.y < 0:
		next_maps[Vector2.UP] = map
	# 下
	elif d.y > 0:
		next_maps[Vector2.DOWN] = map


##  获取地图的中心位置
func get_map_center_pos() -> Vector2:
	var pos = get_used_rect().size * cell_size / 2
	return global_position + pos


##  地图闭合（这样这个路口就无法通过了）
const Directions = [Vector2.LEFT, Vector2.RIGHT, Vector2.UP, Vector2.DOWN]
func close():
	var area_map = {
		Vector2.LEFT: $Left,
		Vector2.RIGHT: $Right,
		Vector2.UP: $Up,
		Vector2.DOWN: $Down,
	}
	for dir in Directions:
		if not next_maps.has(dir):
			area_map[dir].close()



#==================================================
#   内置方法
#==================================================
func _enter_tree():
	# 设置地图区域
	$MapArea.position = Vector2(0,0)
	$MapArea/CollisionShape2D.shape.extents = get_used_rect().size * cell_size / 2
	$MapArea/CollisionShape2D.position = get_used_rect().size * cell_size / 2



#==================================================
#   连接信号方法
#==================================================
## 进入这个地图
func _on_MapArea_area_entered(area):
	emit_signal("entered_map", self)
	
	# 防止进入到这个地图后，碰到了其中的路口区域
	# 然后会立即跳回去，造成无限循环，可以注释掉
	yield(get_tree().create_timer(0.05), "timeout")
	
	open = true


func _on_MapArea_area_exited(area):
	open = false


onready var Map = get_script()
func _on_area_entered(area: Area2D, dir: Vector2):
	if open:
		if next_maps.has(dir):
			var next_map = next_maps[dir]
			if next_map is Map:
				emit_signal("entered_intersection", next_map, next_map.get_delivery(dir))


